import { Message } from 'iview'
import Axios from 'axios'
import Cookies from 'js-cookie'

const baseURL = 'http://127.0.0.1:7001'
// 配置全局的 axios 默认值
Axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
Axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'

const TOKEN_KEY = 'token'
class httpRequest {
  constructor() {
    this.options = {
      method: '',
      url: ''
    }
    // 存储请求队列
    this.queue = {}
  }
  // 销毁请求实例
  destory(url) {
    delete this.queue[url]
    const queue = Object.keys(this.queue)
    return queue.length
  }
  // 请求拦截
  interceptors(instance, url) {
    instance.interceptors.request.use(
      config => {
        if (Cookies.get(TOKEN_KEY)) {
          config.headers['Authorization'] = 'Bearer ' + Cookies.get(TOKEN_KEY)
        }
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截器
    instance.interceptors.response.use(
      res => {
        let { data } = res
        const is = this.destory(url)
        // if (!is) {}
        if (data.code) {
          Message.error(data.error)
        }

        if (res.status !== 200) {
          if (res.status == 401) {
            Cookies.set(TOKEN_KEY, '')
            window.location.href = window.location.pathnamee + '#/login'
            Message.error('登录失效')
          } else {
            Message.error('服务器内部错误')
          }
          return false
        }
        return data
      },
      error => {
        try {
          const status = JSON.parse(JSON.stringify(error)).response.status
          if (status == 401) {
            Cookies.set(TOKEN_KEY, '')
            Message.error('未登录，或登录失效，请登录')
            setTimeout(() => {
              window.location.href = window.location.pathname + '#/login'
              window.location.reload()
            }, 200)
          }
        } catch (err) {
          Message.error('服务器内部错误')
        }
        return Promise.reject(error)
      }
    )
  }
  // 创建axios实例
  create() {
    let conf = {
      baseURL,
      timeout: 8000
      //ithCredentials:true
    }
    return Axios.create(conf)
  }
  // 请求实例
  request(options) {
    let instance = this.create()
    this.interceptors(instance, options.url)
    options = Object.assign({}, options)
    this.queue[options.url] = instance
    return instance(options)
  }
}
export default httpRequest
